import ReactDOM from 'react-dom'
import { useState, useEffect } from 'react'

const Counter = () => {
  console.log('1 render Counter')

  const [count, setCount] = useState(0)
  const onClick = () => {
    setCount(count + 1)
  }
  const [isLoading, setIsLoading] = useState(true)
  const handleLoading = () => {
    setIsLoading(!isLoading)
  }

  const [songs, setSongs] = useState(['痴心绝对', '南山南', '成都'])
  const handleSongs = () => {
    setSongs(['好汉歌', ...songs])
  }
  // 使用useEffect进行dom操作
  useEffect(() => {
    console.log('2 run effect')
    document.title = `当前点击${count}次`
  }, [count])


  // 再次调用useEffect来给windows绑定事件
  useEffect(() => {
    console.log('3 only render once')
    const handleMove = () => {
      console.log('鼠标移动了')
    }
    window.addEventListener('mousemove', handleMove)
  }, [])

  // 解绑事件
  useEffect(() => {
    const hadleResize = () => {
      console.log('浏览器窗口大小变了')
    }
    window.addEventListener('resize', hadleResize)
    // effect 的返回值相当于是一个清理函数，可以用来执行事件解绑等清理操作，这个清理函数只会在组件卸载的时候执行
    return () => window.removeEventListener('resize', hadleResize)
  }, [])

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={onClick}>加1</button>
      <hr />
      <div>{isLoading ? '加载中' : '数据加载完成'}</div>
      <button onClick={handleLoading}>加载数据</button>
      {songs.map((item, index) => (
        <p key={index + '123'}>{item}</p>
      ))}
      <button onClick={handleSongs}>增加歌曲</button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('root'))
